#include "XMLParser.h"

int XMLParser::parseFile(const char * file)
{
	myFile = new QFile(file);
	nodes = new vector<QDomNode>;

	if(myFile->exists() == false){
		printf("\nXML bestaat niet!\n");
		return -1;
	}	

	QDomDocument doc( "myDocument" );
	doc.setContent( myFile );                        // myFile is a QFile

	QDomElement set = doc.documentElement();   // docElement now refers to the node "xml"

	// we doorlopen de xml file via backtracking
	QDomNode nd = set.firstChild();
	backtrack(nd);

	return 1;

}

void XMLParser::backtrack(QDomNode nd) {

	QDomNode endNode;

	while(!nd.isNull()) {

		nodes->push_back(nd);
	
		QDomNode subnd = nd.firstChild();
		if(!subnd.isNull())
			backtrack(subnd);

		nd = nd.nextSibling();

	}

	nodes->push_back(endNode);
}

int XMLParser::getNameNode(QDomNode * nd, char ** namePtr)
{
	QByteArray ba;

	ba = nd->nodeName().toLatin1();
	*namePtr = new char[strlen(ba.data()) +1];
	strcpy(*namePtr, ba.data());

	return 1;

}

int XMLParser::getValueNode(QDomNode * nd, char * valueName, char ** valuePtr)
{
	QByteArray ba;
	QDomAttr attrTemp;

	attrTemp = nd->attributes().namedItem(QString(valueName)).toAttr();
	ba = attrTemp.value().toLatin1();

	*valuePtr = new char[strlen(ba.data()) +1];
	strcpy(*valuePtr, ba.data());

	return 1;

}

int XMLParser::getPosition(char * name)
{
	// zoek in knopen naar name
	for(int i = 0; i <nodes->size(); i++)
	{
		char * tempName;
		this->getNameNode(&(nodes->at(i)), &tempName);
		
		// name gevonden
		if(strcmp(tempName,name) == 0)
		{
			return i;			
		}

	}

	return -1;
}